<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body {
      margin: 0;
      padding: 0;

    }

    .image {
      position: relative;
      overflow: hidden;
    }

    .imac img {
      display: block;
      position: relative;
      top: 50%;
      left: 50%;
      transform: translate(calc(-50% - 30px), 0);
    }

    h2 {
      font-size: 72px;
      font-family: Helvetica;
      letter-spacing: -.012em;
      width: 290px;
      font-weight: normal;
      position: relative;
      left: 50%;
      position: sticky;
      top: -1px;
      margin: 100px 0;
      padding: 0;
      transform: scale(clamp(0.15, var(--scale), 1));
      transform-origin: 0 0;
    }


    .pinned {
      /* color: red; */
    }
  </style>
</head>

<body>
  <div class="imac">
    <h2 style="--scale: 1">Only 11.5mm. Now that's thin.</h2>
    <div class="image">
      <img
        src="https://www.apple.com/105/media/us/imac-24/2021/5e004d75-3ad6-4bb9-ab59-41f891fc52f0/anim/design-hero/large/flow/flow_startframe.jpg"
        alt="">
    </div>
  </div>

  <script>
    let isPinned = false
    const h2 = document.querySelector('h2')

    const observer = new IntersectionObserver(([e]) => {
      // 没有完全可见
      isPinned = (e.intersectionRatio < 1)
      e.target.classList.toggle("pinned", isPinned)
    }, {
      // 可见度是100%的时候触发回调函数
      threshold: [1]
    })


    observer.observe(h2)

    document.addEventListener('scroll', (e) => {
      if (isPinned) {
        let html = document.documentElement
        let height = parseInt(getComputedStyle(h2).getPropertyValue('height')) + parseInt(getComputedStyle(h2)
          .getPropertyValue('margin-bottom'))
        let marginTop = parseInt(getComputedStyle(h2).getPropertyValue('margin-top'))
        // html.scrollTop获得滚动的像素数
        let scrolled = (html.scrollTop - marginTop) / height


        h2.style.setProperty('--scale', (1 - scrolled))
      }
    })
  </script>
</body>

</html>